<template>
    <div class="min-h-screen login min-w-screen flex justify-center items-center bg-gray-300">
        <div class="flex justify-center items-center flex-col w-[650px]  ">
            <el-image style="width: 150px; height: 150px" :src="image" class="mb-5 rounded-xl" />
            <h2 class="font-bold text-3xl text-gray-400 mb-10">{{ name }}</h2>
            <el-form :model="form" :rules="formRules" ref="formRef">
                <el-form-item prop="username">
                    <el-input v-model="form.username" placeholder="請輸入用戶名">
                        <template #prefix>
                            <el-icon>
                                <user />
                            </el-icon>
                        </template></el-input>
                </el-form-item>
                <el-form-item class="pt-5" prop="password">
                    <el-input v-model="form.password" type="password" show-password placeholder="請輸入密碼"><template #prefix>
                            <el-icon>
                                <lock />
                            </el-icon>
                        </template></el-input>
                </el-form-item>
                <el-form-item class=" pt-5">
                    <el-button @click="onSubmit" class="w-[350px]" round color="#606266" :loading="loading">登錄</el-button>
                </el-form-item>
            </el-form>

        </div>

</div>
</template>

<script setup>

import { ref, onMounted,onBeforeUnmount} from 'vue'
import {login} from '@/api/manager.js'
import {msg} from '@/composables/util.js'
import {useRouter} from 'vue-router'

const image=import.meta.env.VITE_APP_LOG
const name=import.meta.env.VITE_APP_NAME

const router=useRouter();
const form = ref({
    username: "",
    password: ""
})

const formRules=ref({
    username: [{ required: true, message: '用戶名不能為空', trigger: 'blur' },],
    password: [{ required: true, message: '密碼不能為空', trigger: 'blur' },]
})

const formRef=ref(null)
const loading=ref(false)

const onSubmit = () => {
    formRef.value.validate(valid=>{
        if(!valid) return  
        login(form.value).then(res=>{
            loading.value=true
            localStorage.setItem('token',res.token)
            msg('登錄成功')
            router.push('/')
            
        }).catch(err=>{
            loading.value=false
        })
    })
}

//键盘监听事件

function onKeyup(e){
    if(e.key == "Enter") onSubmit()
}

onMounted(()=>{
    document.addEventListener('keyup',onKeyup)
})

onBeforeUnmount(()=>{
    document.removeEventListener("keyup",onKeyup)
})
</script>

<style>
/* .login{
    background:linear-gradient(#141e30,#606266);
    background: url(../zzpic24477.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-position: center 0;
} */


</style>